// ml278
// Copyright (C) 2008 Bjørn Øivind Bjørnsen, Aleksander Gjermundsen, Knut Andre Tidemann, Thomas Hansen
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

#include <string>
#include <iostream>
#include <cstdio>
#include <cstdlib>

using namespace std;


int main(int argc, char *argv[])
{
	if(argc < 5)
	{
		cout << "Usage: " << argv[0] << " <mapname> <ZoneSize> <Heightmap width> <output name>" << endl;
		return 1;
	}

	unsigned int zoneSize = atoi(argv[2]);
	unsigned int zonewidth = atoi(argv[3]);

	if(zoneSize == 0 || zonewidth == 0)
	{
		cout << "Invalid values." << endl;
		cout << "Usage: " << argv[0] << " <mapname> <ZoneSize> <Heightmap width>" << endl;
		return 2;
	}

	unsigned int pagewidth = ((zonewidth - 1) / zoneSize) + 1;

	unsigned short *buf = new unsigned short[zonewidth * zonewidth];
	unsigned short *pages[zoneSize][zoneSize];
       
	for(unsigned int i = 0; i < zoneSize; i++)
		for(int unsigned j = 0; j < zoneSize; j++)
			pages[i][j] = new unsigned short[pagewidth * pagewidth];

	FILE *fp = fopen(argv[1], "r");

	if(!fp)
	{
		char errormsg[255] = { 0 };
		sprintf(errormsg,"Failed to open file '%s'",argv[1]);
		perror(errormsg);

		return 3;
	}

	// Read the entire file into a buffer
	fread(buf,zonewidth * zonewidth,sizeof(unsigned short),fp);
	fclose(fp);

	for(unsigned int i = 0; i < zoneSize; i++)
	{
		for(unsigned int j = 0; j < zoneSize; j++)
		{
			for(unsigned int k = 0; k < pagewidth; k++)
			{
				for(unsigned int l = 0; l < pagewidth; l++)
				{
					pages[i][j][k * pagewidth + l] = buf[j * (pagewidth - 1) + ( i * ((pagewidth - 1) * zonewidth)) +  (k * zonewidth) + l];
				}
			}
		}
	}

	char nr[7] = { 0 };
	for(unsigned int i = 0; i < zoneSize; i++)
	{
		for(unsigned int j = 0; j < zoneSize; j++)
		{
			sprintf(nr,"_%04d",i * zoneSize + j + 1);
			string fname = argv[4];
			fname += nr;
			FILE *fp = fopen(fname.c_str(),"w+");
			fwrite(pages[i][j],pagewidth * pagewidth,sizeof(unsigned short),fp);
			fclose(fp);
		}
	}

	cout << "Render options: " << endl << "PageVertexSize: " << pagewidth << endl;



	delete[] buf;

	return 0;
}

